package com.arpa.wms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.common.util.excel.EasyExcelUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.dto.LocationDTO;
import com.arpa.wms.domain.dto.LocationExcelDTO;
import com.arpa.wms.domain.entity.Location;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.BatchRuleVO;
import com.arpa.wms.domain.vo.LocationVO;
import com.arpa.wms.domain.vo.WarehouseVO;
import com.arpa.wms.service.ILocationService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 库位 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-08-03
 */
@Api(tags = "库位")
@RestController
@RequestMapping(value = "/location", produces = "application/json;charset=UTF-8")
@Log4j2
public class LocationController {

    private final ILocationService iLocationService;

    public LocationController(ILocationService iLocationService) {
        this.iLocationService = iLocationService;
    }

    /**
     * 获取 库位 列表
     *
     * @param locationDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 库位 列表", notes = "获取 库位 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = LocationVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(LocationDTO locationDTO, HttpServletRequest request) {
        try {

            //登录账号授权的仓库过滤
            locationDTO.setWarehouseCodes(UserUtil.getAuthorizeWarehouseCodes());
            locationDTO.setGroupCode(UserUtil.getBranchCode());
            LocationVO locationVOSum = iLocationService.queryListSum(locationDTO);
            List<LocationVO> locationVOList = iLocationService.queryList(locationDTO);

            Page returnPage = new Page(locationDTO.getPageNum(), locationDTO.getPageSize());
            returnPage.setRecords(locationVOList);
            returnPage.setTotal(locationVOSum.getTotal());
            returnPage.setSumObject(locationVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 库位
     *
     * @param entity  Location
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 库位 ", notes = "添加 库位 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@Validated(Location.Save.class)Location entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            entity.setStatus(StatusEnum.UNACTIVE.getValue());
            Result validResult = iLocationService.validateLocation(entity);
            if (!validResult.isOk()) {
                return validResult;
            }
            iLocationService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取库位详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取库位详情", notes = "获取库位详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "库位code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = LocationVO.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result location(@PathVariable String code, HttpServletRequest request) {
        try {
            LocationVO entity = iLocationService.getLocation(code);
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改库位
     *
     * @param entity  库位
     * @param request
     * @return
     */
    @ApiOperation(value = "修改库位", notes = "修改库位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Validated(Location.Update.class)Location entity, HttpServletRequest request) {
        if (StrUtil.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }

        Result validResult = iLocationService.validateLocation(entity);
        if (!validResult.isOk()) {
            return validResult;
        }
        int updateNum = iLocationService.updateByCode(entity);
        if (updateNum == 0) {
            return Result.error("没有更新数据！code:" + entity.getCode());
        } else {
            return Result.ok("修改成功,更新" + updateNum + "条数据！");
        }
    }

    /**
     * 删除 库位
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 库位 ", notes = "删除 库位 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "库位code", required = true, paramType = "path", dataType = "String")
    })
    @NeedLogin
    @PostMapping(value = "batchdel")
    public Result batchdel(@RequestBody List<String> codes, HttpServletRequest request) {
        try {
            return iLocationService.deleteByCode(codes);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 停用库位
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "启用库位", notes = "启用库位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping("/active")
    public Result active(@RequestBody List<String> codes, HttpServletRequest request) {

        int updateNum = iLocationService.activeStatus(codes);
        int failNum = codes.size() - updateNum;
        return Result.ok("启用成功" + updateNum + "条；失败" + failNum + "条；");

    }

    /**
     * 停用库位
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "停用库位", notes = "停用库位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping("/unactive")
    public Result unactive(@RequestBody List<String> codes, HttpServletRequest request) {
        Map<String, Object> result = iLocationService.unactiveStatus(codes);
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        StringBuilder builder = new StringBuilder();
        builder.append("停用成功" + success + "条；失败" + failNum + "条；");
        return Result.ok(builder.toString());
    }


    /**
     * 获取 库位下拉列表数据
     *
     * @param spaceCode
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 库位下拉列表数据", notes = "获取 库位下拉列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "warehouseCode", value = "仓库code", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "spaceCode", value = "库区code", paramType = "query", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseVO.class))
    @NeedLogin
    @GetMapping("/chooseDataLimit")
    public Result chooseData(@RequestParam(defaultValue = "") String warehouseCode, @RequestParam(defaultValue = "") String spaceCode, @RequestParam(defaultValue = "") String locationName, @RequestParam(defaultValue = "1") String pageNum,@RequestParam(defaultValue = "10") String pageSize,HttpServletRequest request) {
        try {
            LocationVO LocationVO = iLocationService.queryListSumLocation(warehouseCode, spaceCode, locationName,pageNum,pageSize);
            List<LocationVO> locationVOList = iLocationService.findLocationLimit(warehouseCode, spaceCode, locationName,pageNum,pageSize);

            Page returnPage = new Page(Integer.valueOf(pageNum),Integer.valueOf(pageSize));
            returnPage.setRecords(locationVOList);
            returnPage.setTotal(LocationVO.getTotal());
            returnPage.setSumObject(LocationVO);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 获取 库位下拉列表数据
     *
     * @param spaceCode
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 库位下拉列表数据", notes = "获取 库位下拉列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "spaceCode", value = "库区code", paramType = "query", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseVO.class))
    @NeedLogin
    @GetMapping("/chooseData")
    public Result chooseData(@RequestParam(defaultValue = "") String warehouseCode, @RequestParam(defaultValue = "") String spaceCode, @RequestParam(defaultValue = "") String locationName, HttpServletRequest request) {
        try {
            List<LocationVO> locationVOList = iLocationService.findLocation(warehouseCode, spaceCode, locationName);
            return Result.ok().data(locationVOList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }





    /**
     * 获取 库位下拉列表数据，包含临时库区数据
     *
     * @param spaceCode
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 库位下拉列表数据", notes = "获取 库位下拉列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "spaceCode", value = "库区code", paramType = "query", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseVO.class))
    @NeedLogin
    @GetMapping("/chooseAllData")
    public Result chooseAllData(@RequestParam(defaultValue = "") String warehouseCode, @RequestParam(defaultValue = "") String spaceCode, @RequestParam(defaultValue = "") String locationName, HttpServletRequest request) {
        try {
            List<LocationVO> locationVOList = iLocationService.findAllLocation(warehouseCode, spaceCode, locationName);
            return Result.ok().data(locationVOList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 库位导入预览
     *
     * @param filePath
     * @param isView
     * @param request
     * @return
     */
    @ApiOperation(value = "库位 导入 预览", notes = "库位 导入 预览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/importPreviewList")
    public Result importPreviewList(String filePath, Integer isView, HttpServletRequest request) {

        java.net.URL url = null;
        List<LocationExcelDTO> list = null;
        try {
            url = new java.net.URL(filePath);
            list = EasyExcelUtil.read(url.openStream(), LocationExcelDTO.class, 2);
            if (CollUtil.isEmpty(list)) {
                throw new ServiceException("文件内容为空");
            }
        } catch (MalformedURLException e) {
            return Result.error("上传文件有误");
        } catch (IOException e) {
            return Result.error("文件内容为空");
        }
        List<LocationVO> locationList = iLocationService.importPreviewList(list);
            return new Result().data(locationList);
    }


    /**
     * 预览后导入库位
     *
     * @param importCode 预览时生成的导入码
     * @param request
     * @return
     */
    @ApiOperation(value = "库位 导入", notes = "库位 导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/importLocation")
    public Result importLocation(@RequestParam("importCode") String importCode, HttpServletRequest request) {
        try {
            Result result = iLocationService.importLocation(importCode);
            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

}
